//
//  WNNetwork.m
//  Whatnet_iOS
//
//  Created by Bill on 2019/4/16.
//  Copyright © 2019 什么网络. All rights reserved.
//

#import "WNNetwork.h"

#define WNNetworkMgr [[self shared] networkManager]
static WNNetwork *instance = nil;
@interface WNNetwork ()

@property (nonatomic, assign)   AFNetworkReachabilityStatus status;

@end

@implementation WNNetwork

+ (id)startEngine
{
    return [self shared];
}

+ (id)shared
{
    if (instance) return instance;
    return [[self alloc] init];
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}
+ (void)restart
{
    [[self shared] restart];
}
- (void)restart
{
    [self.networkManager.session resetWithCompletionHandler:^{
//        SALog(@"重启成功！");
    }];
}
- (instancetype)init
{
    if (self = [super init]){
        self.networkManager = [[AFHTTPSessionManager alloc] initWithBaseURL:kWNNetworkBaseURL];
        [self.networkManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        [self.networkManager.requestSerializer setTimeoutInterval:20.0f];
        [self.networkManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
        [self.networkManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"c"];
        [self.networkManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [self.networkManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        
        
        
//        Request.Builder builder1 = original.newBuilder()
//        .addHeader("token", userInfo != null ? MD5.doMD5(userInfo.getUserid() + userInfo.getPassword()) : "")
//        .addHeader("userid", userInfo != null ? userInfo.getUserid() : "")
//        .addHeader("password", userInfo != null ? userInfo.getPassword() : "")
//        .addHeader("type", "0")
        
        
        
//        [self.networkManager.requestSerializer setValue:[NSString stringWithFormat:@"%f",[NSDate date].timeIntervalSince1970] forHTTPHeaderField:@"t"];
//        [self.networkManager.requestSerializer setValue:@"" forHTTPHeaderField:@"token"];
        //        self.networkManager.requestSerializer.HTTPShouldHandleCookies = NO;
        
        [self.networkManager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
            NSInteger type = [[parameters objectForKey:kWNParameterType] integerValue];
            
            if ([request.HTTPMethod isEqualToString:@"GET"]) {
                return AFQueryStringFromParameters(parameters);
            }
            
            if (type == WNParameterTypeKeyValue)
                return [NSString keyValueWithDict:parameters];
            else
                return  [NSString JSONStringWithObject:parameters];
            
        }];
        WNBlockSelf blockself = self;
        [self.networkManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            blockself.status = status;
            switch (status) {
                case AFNetworkReachabilityStatusNotReachable:{
//                    [WNTool show:@"当前无网络，请检查网络设置"];
                }break;
                case AFNetworkReachabilityStatusReachableViaWWAN:{
//                      [WNTool show:@"当前为蜂窝网络"];
                    [WNNotice postNotificationName:WNNetStatusChangeStatus object:@(YES)];
                    [blockself.networkManager.dataTasks enumerateObjectsUsingBlock:^(NSURLSessionDataTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
                        [task resume];
                    }];
                }break;
                case AFNetworkReachabilityStatusReachableViaWiFi:{
//                      [WNTool show:@"当前为WiFi网络"];
                    [WNNotice postNotificationName:WNNetStatusChangeStatus object:@(YES)];
                    [blockself.networkManager.dataTasks enumerateObjectsUsingBlock:^(NSURLSessionDataTask * _Nonnull task, NSUInteger idx, BOOL * _Nonnull stop) {
                        [task resume];
                    }];
                }break;
                default:break;
            }
        }];
        [self.networkManager.reachabilityManager startMonitoring];
    }
    return self;
}

+(NSString*)dataTOjsonString:(id)object
{
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

/**
 设置请求头部
 
 @param dict 请求参数
 */
+ (void)setHTTPHeaderField{

    [WNNetworkMgr.requestSerializer setValue:self.userID_String forHTTPHeaderField:@"userid"];
    [WNNetworkMgr.requestSerializer setValue:self.loginManager.userInfo.password forHTTPHeaderField:@"password"];
    [WNNetworkMgr.requestSerializer setValue:@"0" forHTTPHeaderField:@"type"];
    
    NSString *token = [[NSString stringWithFormat:@"%@%@",self.userID_String,self.loginManager.userInfo.password] MD5];
    [WNNetworkMgr.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    
    
    [WNNetworkMgr.requestSerializer setValue:[NSObject.new.loginManager getUDID] forHTTPHeaderField:@"appno"];
    
    
    
    NSLog(@"--请求头部信息：%@",WNNetworkMgr.requestSerializer.HTTPRequestHeaders);
}

+ (NSString *)networkStatus
{
    WNNetwork *network = [WNNetwork shared];
    switch (network.status) {
        case AFNetworkReachabilityStatusNotReachable:return @"无网络";
        case AFNetworkReachabilityStatusReachableViaWWAN:return @"蜂窝网";
        case AFNetworkReachabilityStatusReachableViaWiFi:return @"WiFi";
        default:return @"未知";
    }
}

#pragma mark -  Get请求
+ (NSURLSessionDataTask *)GET:(NSString *)urlString para:(nullable id)para success:(WNRequestSuccess)success
{
    return [self GET:urlString para:para success:success message:nil];
}

+ (NSURLSessionDataTask *)GET:(NSString *)urlString para:(nullable id)para success:(WNRequestSuccess)success failure:(WNRequestFailure)failure{
    return [self GET:urlString para:para success:success failure:failure message:nil controller:nil];
}

+ (NSURLSessionDataTask *)GET:(NSString *)urlString para:(nullable id)para success:(WNRequestSuccess)success message:(nullable NSString *)message
{
    return [self GET:urlString para:para success:success failure:nil message:message controller:nil];
}
+ (NSURLSessionDataTask *)GET:(NSString *)urlString para:(nullable id)para success:(WNRequestSuccess)success failure:(WNRequestFailure _Nullable)failure message:(nullable NSString *)message controller:(nullable UIViewController * )controller
{
    NSLog(@"请求url:%@",urlString);
    NSLog(@"请求参数:%@",para);
    [self setHTTPHeaderField];
    NSURLSessionDataTask *task = [WNNetworkMgr GET:urlString parameters:para progress:^(NSProgress * _Nonnull downloadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求结果:%@",responseObject);
        [self filterResponse:responseObject task:task success:success failure:failure];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求结果:%@",error);
        if (task.state == NSURLSessionTaskStateCanceling){NSLog(@"用户取消操作"); return;} // 人为取消
        [self responseError:error task:task failure:failure];
    }];
    return task;
}

#pragma mark -  Post请求
+ (NSURLSessionDataTask *)POST:(NSString *)urlString para:(id)para success:(WNRequestSuccess)success
{
    return [self POST:urlString para:para success:success failure:nil message:nil controller:nil];
}


+ (NSURLSessionDataTask *)POST:(NSString *)urlString para:(id)para success:(WNRequestSuccess)success failure:(WNRequestFailure)failure{
    return [self POST:urlString para:para success:success failure:failure message:nil controller:nil];
}


+ (NSURLSessionDataTask *)POST:(NSString *)urlString para:(id)para success:(WNRequestSuccess)success message:(NSString *)message
{
    return [self POST:urlString para:para success:success failure:nil message:message controller:nil];
}

+ (NSURLSessionDataTask *)POST:(NSString *)urlString para:(id)para success:(WNRequestSuccess)success failure:(WNRequestFailure _Nullable)failure message:(NSString * _Nullable)message controller:(UIViewController * _Nullable)controller
{
    NSLog(@"请求url:%@",urlString);
    NSLog(@"请求参数:%@",para);
    [self setHTTPHeaderField];
    NSURLSessionDataTask *task = [WNNetworkMgr POST:urlString parameters:para progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求结果:%@",responseObject);
        [self filterResponse:responseObject task:task success:success failure:failure];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求结果:%@",error);
        [self responseError:error task:task failure:failure];

    }];
    return task;
}



#pragma mark - 结果处理
/// 正常代码处理
+ (void)filterResponse:(id)response task:(NSURLSessionDataTask *)task  success:(WNRequestSuccess)success failure:(WNRequestFailure)failure
{
    NSString * code = [response sa_objectForKey:@"code"];
    id data = [response sa_objectForKey:@"message"];
    
    BOOL result = NO;
    
    
    if ([code isEqualToString:@"0000"]) {
        result = YES;
    }else{
        result = NO;
    }
    
    if (result) {
        if (success) {
            success(data);
        }
    }else{
        NSString *err = @"请求失败";
        if ([data isKindOfClass:[NSString class]]) {
            err = data;
        }
        if (failure) {
            failure(code,err);
        }
    }
}

/// 网络代码处理
+ (void)responseError:(NSError *)error task:(NSURLSessionDataTask *)task  failure:(WNRequestFailure)failure
{
    if(failure) failure([@(error.code) stringValue],@"网络错误");//上面做了处理 所以这里msg传nil
}

+ (void)refreshRequestHeader
{
//    NSString *token = [[SAUser currentUser] token];
//    AFHTTPRequestSerializer *requestSerializer = [[self.shared networkManager] requestSerializer];
//    [requestSerializer setValue:token forHTTPHeaderField:@"x-accessToken"];
}
@end
